import org.apache.commons.io.IOUtils
import org.apache.commons.fileupload.util.Streams
import org.apache.commons.fileupload.servlet.ServletFileUpload
import java.io.*;
import com.google.appengine.api.images.* 
import com.pobos.model.*
import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*



/* gets image upload. From Mr. Haki's blog - http://mrhaki.blogspot.com/2009/11/add-file-upload-support-to-groovlets-in.html */
uploads = [:]  // Store result from multipart content.
if (ServletFileUpload.isMultipartContent(request)) {
 def uploader = new ServletFileUpload()  
 def items = uploader.getItemIterator(request)
 while (items.hasNext()) {
	 def item = items.next()
	 def stream = item.openStream()
	 try {
		 if (item.formField) {  // 'Normal' form field.
			 	params[item.fieldName] = Streams.asString(stream,"UTF-8")
		 } else {
			 uploads[item.fieldName] = [
			                            name: item.name,
			                            contentType: item.contentType,
			                            data: IOUtils.toByteArray(stream)
		                            ]
		 }
	 } finally {
		 IOUtils.closeQuietly stream
	 }
 }
 
 
}


def concello = params.concello
def titulo = params.tituloFoto
def ano = params.ano
def descricion = params.descricion
def lugar = params.lugar

//examina uploads
if (uploads['imaxe']?.data && concello && titulo) {
	
	
	byte[] datosImaxe = uploads['imaxe'].data
	Blob blob = new Blob(datosImaxe)
	
	if (datosImaxe.length < (1024*1024)) {
	
		//datastore.withTransaction {
		
		
			 //Obtiene la entity del concello
			 def key = KeyFactory.createKey(Concello.class.simpleName, Long.parseLong(concello))
			 Entity concelloEntity = datastore.get(key)			
			 
			 
			 Text textoDescricion = new Text("")
			 
			 if (descricion) {
				 textoDescricion = new Text(descricion)
			 }
			 

			Foto foto = new Foto([titulo:titulo
			                      ,descricion:textoDescricion
			                      ,imaxe:blob
			                      ,concello: concello
			                      ,nomeConcello: concelloEntity.nome
			                      ,provincia: concelloEntity.provincia
			                      ,lugar:lugar
			                      ,dataCreacion:new Date()
								  ,ano:ano])
			
			 Image oldImage = ImagesServiceFactory.makeImage(datosImaxe) 
		   
		   	 CompositeTransform cp = ImagesServiceFactory.makeCompositeTransform()
		   	 Transform resize = ImagesServiceFactory.makeResize(800,600)
		   	 cp.concatenate( resize )
		   	 
		   	 CompositeTransform cpThumb = ImagesServiceFactory.makeCompositeTransform()
		   	 Transform resizeThumb = ImagesServiceFactory.makeResize(200,150)
		   	 cpThumb.concatenate( resizeThumb )
		   	 
		   	 Image pic = images.applyTransform( cp, oldImage, ImagesService.OutputEncoding.valueOf("JPEG"))
		   	 Image picThumb = images.applyTransform( cpThumb, oldImage, ImagesService.OutputEncoding.valueOf("JPEG"))
		   	 
		   	 Blob blobThumb = new Blob(picThumb.imageData)
		   	 foto.thumb = blobThumb
		   	 foto.save()
		   	 
		   	 
		   	 Item item = new Item([dataCreacion:new Date(),tipo:'FOTO',
		   	                       idConcello:concello, 
		   	                       item:foto.id])
			 
			 item.save()
			 
			 
			
			 /*Entity concelloEntity = c.getEntity(Concello.class.simpleName
					 , Long.parseLong(concello))*/
			 
			if (concelloEntity.items) {
				int numeroItems = concelloEntity.items.size()
				concelloEntity.items << item.id
				concelloEntity.numeroItems = ++numeroItems;
			} else {
				concelloEntity.items = [item.id]
                concelloEntity.numeroItems = 1
			}
			
			concelloEntity.save()
			
			
			def sesion = request.getSession(true)
			def usuarioSession = sesion.getAttribute('usuario')
			
			Entity usuario = obtenUsuarioSesion(usuarioSession)
			def idPerfil = usuario.perfil
			
			Entity perfilEntity = obtenPerfil(idPerfil)
			
			if (perfilEntity.items) {
				int numeroItems = perfilEntity.items.size()
				perfilEntity.items << item.id
				perfilEntity.numeroItems = ++numeroItems;
			} else {
				perfilEntity.items = [item.id]
                perfilEntity.numeroItems = 1
			}
			
			perfilEntity.save()
			
		   	 
			 //response.setContentType(uploads['imaxe'].contentType)
			 //sout << pic.imageData
			 request.mensaxe="Imaxe '$titulo' creada."
			 request.contido=""	
			 forward '/foto.gtpl'
		 
		//} 

		 
	} else {
		request.erro = "A imaxe non pode ser maior de 1 MB!"
		forward '/foto.gtpl'				
	}
	
	
} else {
	request.erro = "Faltan os datos obrigatorios."
	forward '/foto.gtpl'	
}



def obtenUsuarioSesion(String usuarioSesion) {
	def query = new Query(Usuario.class.simpleName)
	query.addFilter("nome", Query.FilterOperator.EQUAL, usuarioSesion)
	def preparedQuery = datastore.prepare(query)
	
	if (preparedQuery.countEntities() == 0) {
		return null;
	} else {
		if(preparedQuery.countEntities() > 1){
			return preparedQuery.asList(withLimit(1))[0]
		}else{
			return preparedQuery.asSingleEntity()
		}
	}
	
}   

def obtenPerfil(Long id) {
	def key = KeyFactory.createKey("Perfil", id)			
	return datastore.get(key)
}  



